package com.example.gfsquadwebviewproject.fragment.setting;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.gfsquadwebviewproject.R;
import com.example.gfsquadwebviewproject.adapter.UpgradeAdapter;
import com.example.gfsquadwebviewproject.bean.BaseBean;
import com.example.gfsquadwebviewproject.bean.setting.school.SchoolBean;
import com.example.gfsquadwebviewproject.data.ConfigData;
import com.example.gfsquadwebviewproject.presenter.http.get.IGet;
import com.example.gfsquadwebviewproject.presenter.http.get.IGetRequest;
import com.example.gfsquadwebviewproject.presenter.http.get.OkhttpGet;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;

public class UpgradeConfigFragment extends Fragment implements IGetRequest {

    String TAG = "UpgradeConfig";
    Context context;

    TextView et_addr_config;
    TextView et_path_config;
    EditText et_class_path_config;

    Button bt_save_url;
    Button bt_save_teachingBuilding_and_className;

    Spinner sp_school_name,sp_teaching_building,sp_class_number;
    UpgradeAdapter schoolNameAdapter,teachingBuildingAdapter,classNumberAdapter;
    List<String> schoolNameList, buildingNamelist, classNamelist;
    List<String> schoolIdList, buildingIdlist, classIdlist;

    String schoolNameStr = null;
    String buildingNameStr = null;
    String classNumberStr = null;
    String classIdStr = null;

    int schoolNamePosition = 0;
    int teachingBuildingPosition = 0;
    int classNumberPosition = 0;

    ConfigData configData;
    Gson gson;
    IGet iGet;

    final static int IREQUEST_SCHOOL = 1;//GET请求  校区
    final static int IREQUEST_BUILDING = 2;//GET请求 教学楼
    final static int IREQUEST_CLASSROOM = 3;//GET请求 课室编号

    Handler handler = new Handler();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getContext();
        configData = new ConfigData(context);

        schoolNameList = new ArrayList<>();
        schoolIdList = new ArrayList<>();

        buildingIdlist = new ArrayList<>();
        buildingNamelist = new ArrayList<>();

        classIdlist = new ArrayList<>();
        classNamelist = new ArrayList<>();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
       View view = inflater.inflate(R.layout.setting_upgrade_config,container,false);
        sp_school_name = view.findViewById(R.id.sp_school_name);
        sp_class_number = view.findViewById(R.id.sp_class_number);
        sp_teaching_building = view.findViewById(R.id.sp_teaching_building);

        et_addr_config = view.findViewById(R.id.et_addr_config);
        et_path_config = view.findViewById(R.id.et_path_config);
        et_class_path_config = view.findViewById(R.id.et_class_path_config);
        bt_save_url = view.findViewById(R.id.bt_save_url);
        bt_save_teachingBuilding_and_className = view.findViewById(R.id.bt_save_teachingBuilding_and_className);

        et_addr_config.setText(configData.getAddr());
        et_path_config.setText(configData.getPath());
        et_class_path_config.setText(configData.getClass_path());

        schoolNameAdapter = new UpgradeAdapter(getContext(),schoolNameList);
        sp_school_name.setAdapter(schoolNameAdapter);

        classNumberAdapter = new UpgradeAdapter(getContext(), classNamelist);
        sp_class_number.setAdapter(classNumberAdapter);

        teachingBuildingAdapter = new UpgradeAdapter(getContext(), buildingNamelist);
        sp_teaching_building.setAdapter(teachingBuildingAdapter);


        sp_class_number.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                if (position>0) {
                    Log.d(TAG, "sp_class_number position:" + position);
                    classNumberStr = classNamelist.get(position);
                    classIdStr = classIdlist.get(position);
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        sp_teaching_building.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                Log.d(TAG,"sp_teaching_building position:"+position);

                if (position>0) {
                    buildingNameStr = buildingNamelist.get(position);
                    String url = configData.getAddr() + configData.getClass_path() +
                            "type=classroom&id="+buildingIdlist.get(position);
                    iGet.get(url,IREQUEST_CLASSROOM);
                }
                else{
                    initClassromm();
                    classNumberAdapter.notifyDataSetChanged();
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        sp_school_name.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                Log.d(TAG,"sp_school_name position:"+position);
                schoolNameStr = schoolNameList.get(position);
                String url =  configData.getAddr() + configData.getClass_path() + "type=building&id="+schoolIdList.get(position);
                if (position>0) {
                    iGet.get(url,IREQUEST_BUILDING);
                }
                else{
                    initBuilding();
                    teachingBuildingAdapter.notifyDataSetChanged();
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        //保存URL地址
        bt_save_url.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String addr = et_addr_config.getText().toString().trim();
                String path = et_path_config.getText().toString().trim();
                String class_path = et_class_path_config.getText().toString().trim();

                if (addr.length()<6 || !addr.contains("http")){
                    et_addr_config.setError("请输入正确的地址");
                    return;
                }

                if (path.length()<6){
                    et_path_config.setError("请输入正确的路径");
                    return;
                }

                if (class_path.length()<6){
                    et_class_path_config.setError("请输入正确的路径");
                }

                configData.setAddr(addr);
                configData.setPath(path);
                configData.setClass_path(class_path);
                Toast.makeText(context,"保存完成",Toast.LENGTH_SHORT).show();
            }
        });


        //保存教学楼名称和教室编号
        bt_save_teachingBuilding_and_className.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (buildingNameStr !=null && buildingNameStr.length()>1
                        && classNumberStr!=null && classNumberStr.length()>1
                        && schoolNameStr!=null && schoolNameStr.length()>1 ){
                    configData.saveTeachingBuildingName(buildingNameStr);
                    configData.saveClassNumber(classNumberStr);
                    configData.saveClassId(classIdStr);
                    configData.saveSchoolName(schoolNameStr);
                    Toast.makeText(getContext(),"保存课室信息完成："+schoolNameStr+ buildingNameStr +classNumberStr,Toast.LENGTH_SHORT).show();
                    Log.d(TAG,"Url:"+configData.getUrl_Param());
                }
                else {
                    Toast.makeText(getContext(),"请填写正确的课室",Toast.LENGTH_SHORT).show();
                }
            }
        });

        gson = new Gson();
        iGet = new OkhttpGet(this,context);
        String url = configData.getAddr() + configData.getClass_path() + "type=school";
        iGet.get(url,IREQUEST_SCHOOL);
    }

    //校区下拉列表数据
    private void initSchool(){
        schoolNameList.clear();
        schoolIdList.clear();
        schoolIdList.add("");
        schoolNameList.add("—");
        schoolNamePosition = 0;
        schoolNameStr = configData.getSchoolName();
    }

    //教学楼下拉列表数据
    private void initBuilding(){
        buildingIdlist.clear();
        buildingNamelist.clear();
        buildingIdlist.add("");
        buildingNamelist.add("—");
        teachingBuildingPosition = 0;
        buildingNameStr = configData.getTeachingBuildingName();
    }

    //课室编号下拉列表数据
    private void initClassromm(){
        classIdlist.clear();
        classNamelist.clear();

        classNamelist.add("—");
        classIdlist.add("—");

        classNumberPosition = 0;
        classNumberStr = configData.getClassNumber();
    }


    @Override
    public void requestBackMsg(String msg, int methodType, int requestStatus) {
        try {
            BaseBean baseBean = gson.fromJson(msg, BaseBean.class);
            if (baseBean != null && baseBean.getErrCode().equals("200")) {

                SchoolBean schoolBean = gson.fromJson(msg, SchoolBean.class);
                int size = schoolBean.getData().size();

                if (methodType == IREQUEST_SCHOOL) {
                    Log.d(TAG, "校区:" + msg);
                    initSchool();

                    for (int i = 0; i < size; i++) {
                        schoolIdList.add(schoolBean.getData().get(i).getId());
                        schoolNameList.add(schoolBean.getData().get(i).getName());
                    }

                    int schoolNameSize = schoolNameList.size();
                    for (int i = 0; i < schoolNameSize; i++) {
                        if (schoolNameList.get(i).equals(schoolNameStr)) {
                            schoolNamePosition = i;
                            break;
                        }
                    }

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            schoolNameAdapter.notifyDataSetChanged();
                            sp_school_name.setSelection(schoolNamePosition, true);
                        }
                    });

                } else if (methodType == IREQUEST_BUILDING) {
                    Log.d(TAG, "教学楼:" + msg);
                    initBuilding();
                    for (int i = 0; i < size; i++) {
                        buildingIdlist.add(schoolBean.getData().get(i).getId());
                        buildingNamelist.add(schoolBean.getData().get(i).getName());
                    }

                    int buildingNameSize = buildingNamelist.size();
                    for (int i = 0; i < buildingNameSize; i++) {
                        if (buildingNamelist.get(i).equals(buildingNameStr)) {
                            teachingBuildingPosition = i;
                            break;
                        }
                    }

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            teachingBuildingAdapter.notifyDataSetChanged();
                            sp_teaching_building.setSelection(teachingBuildingPosition, true);
                        }
                    });
                } else if (methodType == IREQUEST_CLASSROOM) {
                    Log.d(TAG, "课室:" + msg);
                    initClassromm();
                    for (int i = 0; i < size; i++) {
                        classIdlist.add(schoolBean.getData().get(i).getId());
                        classNamelist.add(schoolBean.getData().get(i).getName());
                    }

                    int classNumberSize = classNamelist.size();
                    for (int i = 0; i < classNumberSize; i++) {
                        if (classNamelist.get(i).equals(classNumberStr)) {
                            classNumberPosition = i;
                            break;
                        }
                    }

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            classNumberAdapter.notifyDataSetChanged();
                            sp_class_number.setSelection(classNumberPosition, true);
                        }
                    });
                }
            } else {
                Log.d(TAG, "msg:" + msg);
            }
        }
        catch (Exception e){
            Log.d(TAG,"requestBackMsg error:"+e);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

}
